import { getCartList, changeCount, deleteCart, getCartTotal } from '@/api/addCart'
import { Toast } from 'vant'
export default {
  namespaced: true,
  state: {
    cartList: [],
    cartTotal: 0
  },
  mutations: {
    setCartLiat (state, cartList) {
      state.cartList = cartList
    },
    // 商品选中状态切换
    toggleCheck (state, goodsId) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    // 全选，反选状态切换
    toggleAllCheck (state, flag) {
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    // 修改商品数量
    changeCount (state, { goodsId, goodsNum }) {
      const obj = state.cartList.find(item => item.goods_id === goodsId)
      obj.goods_num = goodsNum
    },
    // 设置购物车总数
    setCartTotal (state, cartTotal) {
      state.cartTotal = cartTotal
    }
  },
  actions: {
    async getCartAction (context) {
      const { data } = await getCartList()
      // 后台数据中,不包括商品的选中状态,所以需要手动添加
      // 这里假设所有商品都是选中状态
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartLiat', data.list)
    },
    async changeCountAction (context, obj) {
      const { goodsId, goodsNum, goodsSkuId } = obj
      // console.log(obj)
      // 先同步本地
      context.commit('changeCount', {
        goodsId,
        goodsNum
      })
      // 再同步后台
      await changeCount(goodsId, goodsNum, goodsSkuId)
    },
    // 删除购物车数据
    async deleteCartAction (context) {
      const selCartList = context.getters.selCartList
      const cartIds = selCartList.map(item => item.id)
      await deleteCart(cartIds)
      Toast('删除成功')

      // 重新拉取最新的购物车数据（重新渲染）
      context.dispatch('getCartAction')
    },
    // 按需选择删除购物车数据
    async selDeleteAction (context, selID) {
      await deleteCart([selID])
      Toast('删除成功')

      // 重新拉取最新的购物车数据（重新渲染）
      context.dispatch('getCartAction')
    },
    // 获取购物车总数
    async getCartTotalAction (context) {
      const { data: { cartTotal } } = await getCartTotal()
      context.commit('setCartTotal', cartTotal)
    }
  },
  getters: {
    // 购物车商品总数
    // cartTotal (state) {
    //   return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    // },
    // 判断是否选中
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 选中商品数
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中商品总价
    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item) => {
        return sum + item.goods_num * item.goods.goods_price_min
      }, 0).toFixed(2)
    },
    // 商品全选状态
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
